package com.itbaizhan.idempotency;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

/**
 * @author spf
 * @date 2024/4/27
 * @time 11:14
 */
@Component
public class ApiIdempotentInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        boolean present = method.isAnnotationPresent(ApiIdempotentAnn.class);
        if (present && method.getAnnotation(ApiIdempotentAnn.class).value()){
            boolean result = checkToken(request);
            if (result){
                return true;
            }else {
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().write("重复调用");
                return false;
            }
        }
        return false;
    }

    private boolean checkToken(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (null == token || "".equals(token)){
            return false;
        }
        return stringRedisTemplate.delete(token);
    }
}
